using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using ServBus.ListForm2010.License;
using ServBus.ListForm2010.Resources;
using ServBus.ListForm2010.Utility;

namespace ServBus.ListForm2010.Feature
{
    public class WebFeatureReceiver : SPFeatureReceiver
    {
        private static DllResource LICENSE_RESOURCE = new DllResource("ServBus.ListForm2010.Common.Resources|License");

        internal static void EnsureDoclib(SPWeb web)
        {
            bool haslib = false;
            SPList doclib = null;

            // Check if Contains
            if (web.Properties.ContainsKey(Constants.ATT_LIB_KEY))
            {
                try
                {
                    Guid doclibId = new Guid(web.Properties[Constants.ATT_LIB_KEY]);
                    doclib = web.Lists[doclibId];
                    if (doclib.BaseType == SPBaseType.DocumentLibrary)
                        haslib = true;
                }
                catch
                {
                }
            }

            // Create New
            if (!haslib)
            {
                try
                {
                    Guid doclibId = web.Lists.Add(Constants.ATT_LIB_NAME, "", SPListTemplateType.DocumentLibrary);
                    doclib = web.Lists[doclibId];
                    doclib.Hidden = true;
                    doclib.Update();

                    web.Properties[Constants.ATT_LIB_KEY] = doclibId.ToString();
                    web.Properties.Update();
                }
                catch (Exception ex)
                {
                    ErrorLog.Write(ex.Message + Environment.NewLine + ex.StackTrace,
                        System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }

        internal static void RemoveDoclib(SPWeb web, bool noLog)
        {
            try
            {
                Guid doclibId = new Guid(web.Properties[Constants.ATT_LIB_KEY]);
                SPList doclib = web.Lists[doclibId];
                doclib.Delete();

                web.Properties[Constants.ATT_LIB_KEY] = null;
                web.Properties.Update();
            }
            catch (Exception ex)
            {
                if (!noLog)
                {
                    ErrorLog.Write(ex.Message + Environment.NewLine + ex.StackTrace,
                        System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            string errorMsg = null;


            // Check Session
            if (HttpContext.Current.Session == null)
            {
                throw new SPException(LICENSE_RESOURCE.GetString("Session_Disabled"));
            }
            
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPWeb currentWeb = properties.Feature.Parent as SPWeb;
                using (SPSite site = new SPSite(currentWeb.Site.ID))
                {
                    SPWebApplication webapp = site.WebApplication;
                    Activations acts = new Activations(webapp);
                    bool isValid = acts.IsValid(true, out errorMsg);
                    if (isValid)
                    {
                        acts = new Activations(webapp);
                        acts.AddActivation(new ActivationInfo(site, currentWeb));
                        acts.PersistActivation();

                        // Double Check
                        Activations checkActs = new Activations(webapp);
                        if (!checkActs.IsActivationValid_feature(currentWeb, out errorMsg))
                        {
                            
                            errorMsg = LICENSE_RESOURCE.GetString("Activation_Conflict");
                        }
                        else
                        {
                            // Check Library
                            EnsureDoclib(currentWeb);
                            EnsureLookupConfigList(currentWeb);
                        }
                    }
                }
            });
            if (!string.IsNullOrEmpty(errorMsg))
                throw new SPException(errorMsg);
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPSecurity.RunWithElevatedPrivileges(() =>
            {
                SPWeb currentWeb = properties.Feature.Parent as SPWeb;
                using (SPSite site = new SPSite(currentWeb.Site.ID))
                {
                    SPWebApplication webapp = site.WebApplication;
                    Activations acts = new Activations(webapp);
                    acts.DeleteActivation(currentWeb.ID);
                    acts.PersistActivation();

                    // Remove
                    RemoveDoclib(currentWeb, false);
                    RemoveLookupConfigList(currentWeb, false);
                }
            });
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        internal static void EnsureLookupConfigList(SPWeb web)
        {
            bool haslib = false;
            SPList doclib = null;

            // Check if Contains
            if (web.Properties.ContainsKey(Constants.LookupForm_Config_KEY))
            {
                try
                {
                    Guid doclibId = new Guid(web.Properties[Constants.LookupForm_Config_KEY]);
                    doclib = web.Lists[doclibId];
                    if (doclib.BaseType == SPBaseType.GenericList)
                        haslib = true;
                }
                catch
                {
                }
            }

            // Create New
            if (!haslib)
            {
                try
                {
                    Guid doclibId = web.Lists.Add(Constants.LookupForm_Config_NAME, "", SPListTemplateType.GenericList);
                    doclib = web.Lists[doclibId];
                    doclib.Fields.Add("mContentType", SPFieldType.Text, false);
                    doclib.Fields.Add("mDispView", SPFieldType.Text, false);
                    doclib.Fields.Add("mEditView", SPFieldType.Text, false);
                    doclib.Fields.Add("mNewView", SPFieldType.Text, false);                    
                    doclib.Fields.Add("sTitle", SPFieldType.Text, false);
                    doclib.Fields.Add("sContentType", SPFieldType.Text, false);
                    doclib.Hidden = true;
                    doclib.Update();

                    web.Properties[Constants.LookupForm_Config_KEY] = doclibId.ToString();
                    web.Properties.Update();
                }
                catch (Exception ex)
                {
                    ErrorLog.Write(ex.Message + Environment.NewLine + ex.StackTrace,
                        System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }

        internal static void RemoveLookupConfigList(SPWeb web, bool noLog)
        {
            try
            {
                Guid doclibId = new Guid(web.Properties[Constants.LookupForm_Config_KEY]);
                SPList doclib = web.Lists[doclibId];
                doclib.Delete();

                web.Properties[Constants.LookupForm_Config_KEY] = null;
                web.Properties.Update();
            }
            catch (Exception ex)
            {
                if (!noLog)
                {
                    ErrorLog.Write(ex.Message + Environment.NewLine + ex.StackTrace,
                        System.Diagnostics.EventLogEntryType.Error);
                }
            }
        }
    }
}
